// pages/goodsDetail/goodsDetail.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    show: false,
    goodsInfo: {},
    goodsNumber: 1,
    type: '',
    model: '',
    userScore: 0
  },

  // 兑换窗口
  showPopup: function () {
    this.setData({
      show: true
    })
  },

  // 兑换窗口消失
  onClose: function () {
    this.setData({
      show: false
    })
  },

  numberChange: function (e) {
    // console.log(e.detail)
    this.setData({
      goodsNumber: e.detail
    })
  },

  changeType: function (e) {
    this.setData({
      type: e.currentTarget.dataset.type
    })
  },

  changeModel: function (e) {
    this.setData({
      model: e.currentTarget.dataset.model
    })
  },

  toExchange: function (e) {
    if (this.data.userScore < this.data.goodsInfo.g_score * this.data.goodsNumber) {
      wx.showModal({
        content: '积分不足,快去赚积分吧',
        showCancel: false,
        success: res => {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/task/task',
            })
          }
        }
      })
    } else {
      let goodsInfo = {
        id: this.data.goodsInfo.g_id,
        label: this.data.goodsInfo.g_label.length == 1 ? this.data.goodsInfo.g_label[0] : this.data.type,
        count: this.data.goodsNumber,
        goodsPic: this.data.goodsInfo.g_pic1,
        goodsDesc: this.data.goodsInfo.g_desc,
        goodsScore: this.data.goodsInfo.g_score * this.data.goodsNumber
      }
      wx.navigateTo({
        url: '/pages/exchange/exchange?goodsInfo=' + JSON.stringify(goodsInfo),
      })
      this.setData({
        show: false
      })
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    app.post('Goods/detail', {
      id: options.gid
    }).then(res => {
      this.setData({
        goodsInfo: res.data.result_data,
        type: res.data.result_data.g_label[0]
      })
    }).then(() => {
      app.post('Member/info', {
        token: wx.getStorageSync('token')
      }).then(res => {
        this.setData({
          userScore: res.data.result_data.m_score
        })
      })
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})